package com.roc.util.httpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import com.alibaba.fastjson.JSONObject;

/**
 * @author administrator
 *
 * Http Client工具类
 * 发起http client 请求
 * 
 * 窗口 － 首选项 － Java － 代码样式 － 代码模板
 */
@Component
public final class HttpClientUtil {

	private static final Logger logger = LogManager.getLogger(HttpClientUtil.class);

    private static Map<String, String> headers = new HashMap<String, String>();

    @Value("${sms.url}")
	private String msgurl;

    
    
    static {  
        headers.put("User-Agent",  
                "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.2)");  
        headers.put("Accept-Language", "zh-cn,zh;q=0.5");  
        headers.put("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");  
        headers.put(  
                "Accept",  
                " image/gif, image/x-xbitmap, image/jpeg, "  
                        + "image/pjpeg, application/x-silverlight, application/vnd.ms-excel, "  
                        + "application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*");  
        headers.put("Content-Type", "application/x-www-form-urlencoded");  
        headers.put("Accept-Encoding", "gzip, deflate");  
    }  

    
    /**  
     * 异常或者没拿到返回结果的情况下,result为""  
     *   
     * @param url  
     * @param param  
     * @return  
     */  
    @SuppressWarnings("unchecked")
	public static String httpPost(String url, JSONObject jsonObject) {  
    	logger.info("httpPost URL [" + url + "] start ");  
        CloseableHttpClient httpclient = null;  
        HttpPost httpPost = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;  
        String result = "";  
        StringBuffer suf = new StringBuffer();  
        try { 
            httpclient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom()  
                    .setConnectTimeout(5000*6).setConnectionRequestTimeout(1000*5*6)  
                    .setSocketTimeout(5000*6).build();
            httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            // 设置各种头信息  
            for (Entry<String, String> entry : headers.entrySet()) {  
                httpPost.setHeader(entry.getKey(), entry.getValue());  
            }  
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
            // 传入各种参数  
            if (null != jsonObject) {
                for (Object o : jsonObject.entrySet()) { 
                	Map.Entry<String,String> entry = (Map.Entry<String,String>)o; 
                    String key = entry.getKey();  
                    String value = entry.getValue() == null ? "" : entry.getValue()  
                            .toString();  
                    nvps.add(new BasicNameValuePair(key, value));  
                    suf.append(" [" + key + "-->" + value + "] ");  
                }  
            }  
            logger.info("param " + suf.toString());  
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));  
            response = httpclient.execute(httpPost);  
            int statusCode = response.getStatusLine().getStatusCode();  
            if (statusCode != HttpStatus.SC_OK) {  
            	logger.error("HttpStatus ERROR" + "Method failed: "  
                        + response.getStatusLine());  
                return "";  
            } else {  
                entity = response.getEntity();  
                if (null != entity) {  
                    byte[] bytes = EntityUtils.toByteArray(entity);  
                    result = new String(bytes, "UTF-8");  
                } else {  
                	logger.error("httpPost URL [" + url  
                            + "],httpEntity is null.");  
                }  
                return result;  
            }  
        } catch (Exception e) {  
        	//超过10次异常 5分钟发一次
        
        	logger.error("httpPost URL [" + url + "] error, ", e);  
            return "";  
        } finally {  
            if (null != httpPost) {  
            	httpPost.releaseConnection(); 
            }  
            logger.info("RESULT:  [" + result + "]");  
            logger.info("httpPost URL [" + url + "] end ");  
        }  
    }  
	

}